<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    
    <el-card class="box-card">
      <div slot="header">
        <span>用户数据</span>
      </div>
      <div id="userChart" style="width: 100%; height: 300px;"></div>

    </el-card>
    
    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header">
        <span>景点数据</span>
      </div>
      <div id="attractionChart" style="width: 100%; height: 400px;"></div>

    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'DataDisplay',
  data () {
    return {
      msg: '欢迎来到景点推荐软件管理系统',
      userChart: null,
      attractionChart: null,
      users: [],
      attractions: [],
      totalViews: 0

    }
  },
  mounted() {

    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.initCharts();
    this.fetchUsers();
    this.fetchAttractions();
    this.setChartOptions();
  },
  beforeDestroy() {
    // 移除监听事件
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    handleResize() {
      if (this.userChart) {
        this.userChart.resize();
      }
      if (this.attractionChart) {
        this.attractionChart.resize();
      }
    },
    initCharts() {
      this.userChart = echarts.init(document.getElementById('userChart'));
      this.attractionChart = echarts.init(document.getElementById('attractionChart'));
    },

    setChartOptions() {
      this.userChart.setOption({
        title: {
          text: '用户年龄分布'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [{
          name: '年龄分布',
          type: 'pie',
          radius: '90%',
          data: [
            { value: 2, name: '0-18岁' },
            { value: 3, name: '19-30岁' },
            { value: 1, name: '31-45岁' },
            { value: 1, name: '46-60岁' },
            { value: 1, name: '60岁以上' },
            { value: 5, name: '其他' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      });

      // 对景点按浏览量排序
      const sortedAttractions = [...this.attractions].sort((a, b) => b.visitors - a.visitors);
      const top4 = sortedAttractions.slice(0, 4);
      
      this.attractionChart.setOption({
        title: {
          text: `景点数据统计(总浏览量: ${this.totalViews})`
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: top4.map(item => item.name)
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: '浏览量',
          type: 'bar',
          data: top4.map(item => item.visitors),
          itemStyle: {
            color: function(params) {
              const colorList = ['#c23531','#2f4554','#61a0a8','#d48265','#91c7ae'];
              return colorList[params.dataIndex];
            }
          }
        }]
      });
    },
    async fetchUsers() {

      console.log('fetchUsers')
      try {
        const response = await this.$http.get('/admin/userAgeDistribution');
        if (response.data.code === 200) {
          this.userChart.setOption({
            series: [{
              data: response.data.data.map(item => ({
                value: item.value,
                name: item.name
              }))
            }]
          });
        }
      } catch (error) {
        console.error('获取用户年龄分布数据失败:', error);
      }
    },
    async fetchAttractions() {
      console.log('fetchAttractions')
      try {
        const response = await this.$http.get('/admin/attractionViews');
        if (response.code === 200) {
          console.log(response)
          this.attractions = response.topAttractions.map(item => ({
            name: item.name,
            visitors: item.view_count
          }));
          this.totalViews = response.totalViews;
          this.setChartOptions();
        }
      } catch (error) {
        console.error('获取景点浏览量数据失败:', error);
      }
    },

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}

.box-card {
  /* display: flex; */
  /* flex-direction: column; */
  align-items: center;
  width: 98%;
  height: auto;
  padding: 20px;
}

#userChart, #attractionChart {
  width: 100%;
  height: 100%;
  min-width: 300px;
  min-height: 300px;
}


</style>
